package com.governtalk.backend.repository;

import com.governtalk.backend.entity.StudyGroup;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StudyGroupRepository extends JpaRepository<StudyGroup, Long> {
    
    // 查找公开的活跃小组
    Page<StudyGroup> findByIsPublicTrueAndIsActiveTrue(Pageable pageable);
    
    // 根据分类查找小组
    Page<StudyGroup> findByCategoryIdAndIsPublicTrueAndIsActiveTrue(Long categoryId, Pageable pageable);
    
    // 根据创建者查找小组
    List<StudyGroup> findByCreatorIdAndIsActiveTrue(Long creatorId);
    
    // 搜索小组
    @Query("SELECT sg FROM StudyGroup sg WHERE (sg.name LIKE %:keyword% OR sg.description LIKE %:keyword%) AND sg.isPublic = true AND sg.isActive = true")
    Page<StudyGroup> searchGroups(@Param("keyword") String keyword, Pageable pageable);
    
    // 查找热门小组（按成员数量排序）
    @Query("SELECT sg FROM StudyGroup sg WHERE sg.isPublic = true AND sg.isActive = true ORDER BY sg.currentMembers DESC")
    Page<StudyGroup> findPopularGroups(Pageable pageable);
    
    // 查找最新创建的小组
    @Query("SELECT sg FROM StudyGroup sg WHERE sg.isPublic = true AND sg.isActive = true ORDER BY sg.createdAt DESC")
    Page<StudyGroup> findLatestGroups(Pageable pageable);
    
    // 根据用户ID查找用户加入的小组
    @Query("SELECT sg FROM StudyGroup sg JOIN GroupMember gm ON sg.id = gm.group.id WHERE gm.user.id = :userId AND gm.status = 'ACTIVE' AND sg.isActive = true")
    List<StudyGroup> findGroupsByUserId(@Param("userId") Long userId);
    
    // 检查用户是否是小组创建者
    boolean existsByIdAndCreatorId(Long groupId, Long creatorId);
}

